<template>
  <!-- 地址处理 -->
  <div style="height: 100%;" class="handle-address">
    <div class="hda-top" id="loadMoreSelect">
      <el-select
        v-model="currentHandleFile"
        @change="currentHandleFileChange"
        size="mini"
        placeholder="请选择"
        style="width: 140px"
      >
        <el-option
          :label="item.file_name"
          :value="item.id"
          v-for="item in flieListOptions"
          :key="item.id"
        ></el-option>
      </el-select>
      <div class="hda_steps">
        <template v-for="step in stepDatas">
          <div :key="step.index">
            <!-- <div class="had_step" @click="onStepClick(step.index)"> -->
            <div class="had_step">
              <div
                class="round"
                :class="stepMaps[$store.state.currentFileInfo.id] === step.index ? 'round_on' : 'round_pa'"
              >{{ step.index }}</div>
              <div class="text">{{ step.name }}</div>
              <div class="line" v-if="step.index < 3"></div>
            </div>
          </div>
        </template>
      </div>
      <div>
        <el-button
          type="primary"
          size="mini"
          @click="nextStep(stepMaps[$store.state.currentFileInfo.id])"
          v-if="stepMaps[$store.state.currentFileInfo.id] !== 3"
        >下一步</el-button>
        <el-button type="primary" size="mini" v-else @click="clickDone">导出</el-button>
      </div>
    </div>
    <template v-if="flieListOptions && flieListOptions.length > 0">
      <div v-if="stepMaps[$store.state.currentFileInfo.id] == 1" style="height: 100%;">
        <addrCollect></addrCollect>
      </div>
      <div v-if="stepMaps[$store.state.currentFileInfo.id] == 2" style="height: 100%;">
        <addrCheck></addrCheck>
      </div>
      <div v-if="stepMaps[$store.state.currentFileInfo.id] == 3" style="height: 100%;">
        <addrPass></addrPass>
      </div>
    </template>

    <el-dialog
      class="confirm-convergence_address"
      title="汇聚地址完成二次确认"
      :visible.sync="confirmCovergenceAddressDialogShow"
      :close-on-click-modal="false"
      width="60%"
    >
      <div class="confirm-next_convergence_address">
        <img :src="gth" alt="gth" style="margin-top: 30px;" />
        <div style="font-size:12px; font-weight: 600;margin-top: 10px;">确定完成”汇聚地址“步骤？</div>
        <div class="btn-group">
          <el-button size="mini" type="primary" @click="confirmConvergence">确定</el-button>
          <el-button size="mini" @click="confirmCovergenceAddressDialogShow = false">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import addrCollect from "@/components/addrProcess/addrCollect";
import addrCheck from "@/components/addrProcess/addrCheck";
import addrPass from "@/components/addrProcess/addrPass";

import gth from "@/icons/gth.svg";
import { getTime } from "date-fns/esm";

export default {
  components: {
    addrCollect,
    addrCheck,
    addrPass,
  },
  data() {
    return {
      confirmCovergenceAddressDialogShow: false,
      gth,
      currentHandleFile: "",
      stepDatas: [
        { index: 1, name: "汇聚地址" },
        { index: 2, name: "校验地址" },
        { index: 3, name: "地址回传" },
      ],
      flieListOptions: [],
      currentStep: 1,
      stepMaps: {},
      fileStep: 1,
      currentPage: 1,
      totalflieListOptions: [],
    };
  },
  methods: {
    nextStep(step) {
      // if (this.$store.state.leftChecks.length <= 0) {
      //   this.$message.warning("请先去文件列表点击启动地址处理~");
      //   return;
      // }

      // if (this.currentStep > 2) {
      // this.currentStep = 1;
      // } else
      if (step == 1) {
        this.confirmCovergenceAddressDialogShow = true;
        this.fileStep = step
      } else if(step == 2) {
        this.$confirm('确认要完成校验地址吗，该操作不可回退！', '提示').then(()=>{
          step++;

          this.setCurrentMapStep(
            this.$store.state.currentFileInfo.id,
            step
          );
        }).catch(()=>{return})
      }else if(step == 3) {
        this.setCurrentMapStep(
          this.$store.state.currentFileInfo.id,
          step
        );
      }
    },
    confirmConvergence() {
      this.fileStep++;
      this.confirmCovergenceAddressDialogShow = false;

      this.setCurrentMapStep(
        this.$store.state.currentFileInfo.id,
        this.fileStep
      );
    },
    onStepClick(index) {
      this.currentStep = index;
      // 缓存当前的step
      this.setCurrentMapStep(this.$store.state.currentFileInfo.id, index);
    },
    async clickDone() {
      const res = await this.axios.post(this.apis.addressDataQuery, {
        import_file_record_id: this.$store.state.currentFileInfo.id,
        page: this.currentPage,
        limit: 1000,
        // is_sure_standard_address: true
      });
      if (res.retCode === 2000) {
        const jsonData = (res.rows.items || []).map((item) => ({
          obj_number: item.obj_number,
          obj_name: item.obj_name,
          standard_address: item.standard_address,
          supplementary_address: item.supplementary_address,
          target_address: item.target_address,
        }));
        let str = `对象编号,对象名称,标准地址,补充地址,目标地址\n`;

        for (let i = 0; i < jsonData.length; i++) {
          for (let item in jsonData[i]) {
            str += `${jsonData[i][item] + "\t"},`;
          }
          str += "\n";
        }

        let uri =
          "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(str);
        var link = document.createElement("a");
        link.href = uri;
        link.download = "地址数据.csv";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    },
    getCurrentMapStep(id) {
      let initStep = {}
      this.totalflieListOptions.forEach(item => {
        initStep[item.id] = 1
      })

      let steps = window.localStorage.getItem("stepMaps");
      this.stepMaps = {...initStep, ...JSON.parse(steps)};

      console.log(this.stepMaps, "this.stepMaps");
    },
    setCurrentMapStep(fileid, index) {
      console.log(fileid, index, "fileid, index");
      // this.stepMaps[this.$store.state.currentFileInfo.id] = this.currentStep
      this.stepMaps[fileid] = index;

      window.localStorage.setItem("stepMaps", JSON.stringify(this.stepMaps));
      console.log(this.stepMaps, "stepMaps");
    },
    async getInitData() {
      const res = await this.axios.post(this.apis.importFileRecordQuery, {
        page: 1,
        limit: 1000,
        handle_status: ['处理中', '已完成']
      });
      this.totalflieListOptions = res.rows.items;
      this.flieListOptions = JSON.parse(JSON.stringify(res.rows.items)).splice(
        0,
        10 * this.currentPage
      )
    },
    currentHandleFileChange(e) {
      this.setCurrentMapStep(
        this.$store.state.currentFileInfo.id,
        this.stepMaps[this.$store.state.currentFileInfo.id]
      );

      console.log(e, "e");
      this.$router.push("/addrProcess?id=" + e);
      this.$store.state.currentFileInfo = {
        id: e,
      };

      localStorage.removeItem('checksInLocal')
    },
    //给select框加滚动监测
    setLoadMore() {
      const that = this;
      // if (!document.getElementById('loadMoreSelect')) {
      //   return
      // }
      //获得元素
      // console.log(document.getElementById('loadMoreSelect'), 'xx');
      const loadSelectElement = document
        .getElementById("loadMoreSelect")
        .getElementsByClassName("el-select-dropdown__wrap")[0];
      let timer = null;
      function scrollLoadData() {
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
          const scrollDistance =
            loadSelectElement.scrollHeight -
            loadSelectElement.scrollTop -
            loadSelectElement.clientHeight;
          // 非搜索
          if (scrollDistance <= 0 && !that.query) {
            console.log("触底了");
            //页码依次加1
            let list = JSON.parse(JSON.stringify(that.totalflieListOptions)).splice(
                10* that.currentPage,
                10 * (that.currentPage + 1)
              )
            if (list.length) {
              console.log("有东西可以加一");
              that.flieListOptions = [...that.flieListOptions, ...list]
              that.currentPage++;
            }
          }
        }, 300);
      }
      loadSelectElement.addEventListener("scroll", scrollLoadData);
      //如果已加载完全部数据，取消监听
      if (that.getAll) {
        loadSelectElement.removeEventListener("scroll", scrollLoadData);
      }
    },
  },
  async mounted() {
    console.log("父组件 渲染");
    await this.getInitData();

    // 设置当前的文件id
    let id = this.$route.query.id ? Number(this.$route.query.id) : this.flieListOptions[0].id
    this.currentHandleFile = id

    this.$store.state.currentFileInfo.id = id
    this.getCurrentMapStep();

    this.setLoadMore()
  },
};
</script>

<style>
.confirm-convergence_address .el-dialog__title {
  font-size: 14px;
  font-weight: 600;
}
.confirm-convergence_address .el-dialog__header {
  border-bottom: #ececec 1px solid;
  padding: 10px 20px;
}

.confirm-convergence_address .el-dialog__body {
  padding: 20px;
}

/* .confirm-convergence_address .el-icon-close {
  display: none;
} */

.confirm-next_convergence_address img {
  width: 30px;
  height: 30px;
}
.confirm-next_convergence_address {
  display: flex;
  /* justify-content: center; */
  flex-direction: column;
  align-items: center;
}
.confirm-next_convergence_address .btn-group {
  margin-top: 60px;
}

.handle-address {
  display: flex;
  flex-direction: column;
}

.handle-address .hda-top {
  width: 100%;
  min-width: 860px;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 10px;
}
.hda_steps {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.had_step {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 12px;
}

.round {
  border-radius: 50%;
  width: 25px;
  height: 25px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}
.round_pa {
  background-color: #fff;
  border: 1px solid #bbb;
  color: #bbb;
}
.round_on {
  background-color: hsl(209, 93%, 62%);
  border: 1px solid #ececec;
  color: #fff;
}
.text {
  margin-left: 3px;
}
.line {
  width: 160px;
  height: 1px;
  background-color: #e4e4e4;
  margin: 0 20px;
}
</style>